<?php

namespace App\Http\Controllers\Auth;

use Cartalyst\Sentry\Facades\Laravel\Sentry;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use App\Http\Model\Auth;
use App\Http\Model\Group;

class AuthController extends CommonController
{
    //用户界面
    public function user(Request $request){
    	if($request->isMethod('post')){
	    	$input=Input::all();
			
			$sdb=DB::table('users')->offset($input['pageSize']*($input['pageCurrent']-1))->limit($input['pageSize']);
			$sdb2=DB::table('users');
			
			if(isset($input['orders']) && $input['orders']){
				$orders=explode(',',$input['orders']);
				foreach($orders as $v){
					$order=explode(' ',$v);
					$sdb=$sdb->orderBy($order[0],$order[1]);
				}
			}
			
			foreach($input as $k=>$v){
				if(strpos($k, 'obj_') !== false && !strpos($k, '_operator')){
					if($v==='true'){
						$v=1;
					}elseif($v==='false'){
						$v=0;
					}
					$sdb->where(substr($k,4),'like','%'.$v.'%');
					$sdb2->where(substr($k,4),'like','%'.$v.'%');
				}
			}
			
			$users=$sdb->get();
			
			$c=$sdb2->count();
			$count=ceil($c/$input['pageSize']);

	        foreach($users as $v){
	            $user = Sentry::findUserByID($v->id);
	            $v->group=$user->getGroups();
	        }
			return $input['callback'].'({"lastPage":true,"pageSize":'.$input['pageSize'].',"pageNumber":1,"firstPage":true,"list":'.json_encode($users).',"totalRow":'.$count.',"totalPage":'.$input['pageCurrent'].'})';
		}else{
        	return view('admin.user.user');
		}
    }
	
	
	public function userEdit(){
		$input=Input::all();
		$groups = Sentry::findAllGroups();
		if(isset($input['id']) && $input['id']){
			$user=Sentry::findUserById($input['id']);
	        if(count($user->getGroups())>0){
	            $group = $user->getGroups();
				$groupid=[];
				foreach($group as $v){
					$groupid[]=$v->id;
				}
	        }else{
	            $groupid = [];
	        }
			
			$method='edit';
			return view('admin.user.userEdit',compact('groups','groupid','user','method'));
		}else{
			$method='add';
        	return view('admin.user.userEdit',['groups'=>$groups,'method'=>$method]);
		}
	}
	
    //创建用户
    public function createUser(){
    	$input=Input::all();
        $rules=[
            'email'=>'required|email',
            'password'=>'between:6,20',
        ];
        $message=[
            'password.between'=>'密码范围必须在6-20位之间！',
            'email.required' => '必须填写登录邮箱',
            'email.email' => '请填写正确的邮箱',
        ];
        $validator=Validator::make($input,$rules,$message);
		
		$ret=[
			"status"=>300,
			"msg"=>"添加用户失败"
		];
			
        if(!$validator->passes()){
			$ret['msg']=$validator->messages()->first();
        }
        try
        {
            $input = Input::except('_token');
            $user = Sentry::createUser(array(
                'email'     => $input['email'],
                'password'  => $input['password'],
                'nickname'  => $input['nickname'],
                'activated' => true,
            ));
            // 查找用户组 where 为 组id ＝ 1
            if(isset($input['g_id'])){
	            foreach($input['g_id'] as $v){
	                $adminGroup = Sentry::findGroupById($v);
	                // 把 用户加到 用户组
	                $user->addGroup($adminGroup);
	            }
			}
			$ret['status']=200;
			$ret['msg']='添加用户成功!';
			$ret['tabid']='user';
        }
        catch (\Cartalyst\Sentry\Users\LoginRequiredException $e)
        {
        	$ret['msg']='登录帐号(邮箱不存在)!';
        }
        catch (\Cartalyst\Sentry\Users\PasswordRequiredException $e)
        {
        	$ret['msg']='没有提供密码,请稍后重试!';
        }
        catch (\Cartalyst\Sentry\Users\UserExistsException $e)
        {
        	$ret['msg']='用户已经存在,请稍后重试!';
        }
        catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e)
        {
        	$ret['msg']='用户不存在,请稍后重试!';
        }
		return $ret;
    }
    //修改用户
    public function editUser(){
    	$input=Input::all();
        $rules=[
            'password'=>'between:6,20|confirmed',
        ];
        $message=[
            'password.between'=>'新密码范围必须在6-20位之间！',
            'password.confirmed'=>'新密码和确认密码不一致！',
        ];
		
		$ret=[
			"status"=>300,
			"msg"=>"修改用户失败"
		];
		
        try
        {
            // 通过 分组ID 查找分组
            $user = Sentry::findUserById($input['id']);
			
            // 更新分组详情
            DB::table('users_groups')->where('user_id',$input['id'])->delete();
            if(isset($input['g_id'])){
	            foreach($input['g_id'] as $v){
	                $adminGroup = Sentry::findGroupById($v);
	                // 把 用户加到 用户组
	                
		            if (!$user->addGroup($adminGroup)){
						$ret['msg']='用户组绑定失败,请重试!';
		            }
	            }
			}
            $user->nickname = $input['nickname'];

            if($input['password']){
                $validator=Validator::make($input,$rules,$message);

                if(!$validator->passes()){
                    $ret['msg']=$validator->messages()->first();
                }
                $user->password = $input['password'];
            }
            // 更新分组
            if ($user->save())
            {
				$ret['status']=200;
				$ret['msg']='用户修改成功!';
				$ret['tabid']='user';
            }else{
				$ret['msg']='用户修改失败,请重试!';
            }
        }
        catch (\Cartalyst\Sentry\Users\UserExistsException $e) {
			$ret['msg']='用户登录邮箱必须存在,请重试!';
        }
        catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
			$ret['msg']='用户不存在,请重试!';
        }
		return $ret;
    }
    //删除用户
    public function delUser(){
       	$input=Input::all();		
        $id = explode(",", $input['id']);
		
        foreach($id as $v){
        	try {
        		if($v){
            		Sentry::findUserById($v)->delete();
				}
			}catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
                $data = [
                    'status' => 300,
                    'msg' => '用户不存在-'.$v.'，请重试！',
                ];
				return $data;
            }
        }
		$data = [
            'status' => 200,
            'msg' => '用户删除成功！',
        ];
        return $data;
    }



    //用户组界面
    public function group(Request $request){
    	if($request->isMethod('post')){
    		$input=Input::all();
    		$group=Group::offset($input['pageSize']*($input['pageCurrent']-1))->limit($input['pageSize']);
			
			
			if(isset($input['orders']) && $input['orders']){
				$orders=explode(',',$input['orders']);
				foreach($orders as $v){
					$order=explode(' ',$v);
					$group=$group->orderBy($order[0],$order[1]);
				}
			}
			
			foreach($input as $k=>$v){
				if(strpos($k, 'obj_') !== false && !strpos($k, '_operator')){
					$group->where(substr($k,4),'like','%'.$v.'%');
				}
			}
			

			$list['list']=$group->get()->toArray();
			$list['firstPage']=true;
			$list['lastPage']=true;
			$list['pageNumber']=1;
			$list['pageSize']=$input['pageSize'];
			$list['totalPage']=$input['pageCurrent'];
			$list['totalRow']=$group->count();

			return $input['callback'].'('.json_encode($list).')';
    	}else{
	        $groups=DB::table('groups')->get();
	        return view('admin.user.group');
		}
    }
	
	public function groupEdit(){
		$input=Input::all();
		$auth=Auth::all();
		if(isset($input['id']) && $id=$input['id']){
			$group=Sentry::findGroupById($input['id']);
	        $groupPermissions = $group->getPermissions();
			$ids=[];
			$names=[];
			$roles=[];
			foreach($groupPermissions as $k=>$v){
				foreach($auth as $r){
					if($k==$r->role){
						$ids[]=$r->id;
						$names[]=$r->name;
						$roles[]=$r->role;
						break;
					}
				}
			}
			$ids=json_encode($ids);
			$names=implode(',', $names);
			$roles=implode(',', $roles);
			$method='edit';
			return view('admin.user.groupEdit',compact('auth','ids','group','method','roles','names'));
		}else{
			$method='add';
        	return view('admin.user.groupEdit',['method'=>$method,'auth'=>$auth]);
		}
	}

    //创建用户组界面
    public function createGroup(){
        $input=Input::all();
        try
        {
			foreach(explode(',',$input['roles']) as $v){
				$roles[$v]=1;
			}
            // 创建分组
            $group = Sentry::createGroup(array(
                'name'=> $input['name'],
                'permissions' =>$roles,
            ));
            $ret = [
                'status' => 200,
                'msg' => '添加角色成功!',
                'tabid'=>'group'
            ];
        }

        catch (\Cartalyst\Sentry\Groups\NameRequiredException $e){
            $ret = [
                'status' => 300,
                'msg' => '角色名称必须存在!',
            ];
        }
        catch (\Cartalyst\Sentry\Groups\GroupExistsException $e){
            $ret = [
                'status' => 300,
                'msg' => '角色已经存在!',
            ];
        }
        return $ret;
    }

    //修改用户组界面
    public function editGroup(){
        $input=Input::all();
        try
        {
        	foreach(explode(',',$input['roles']) as $v){
				$roles[$v]=1;
			}
            // 通过 分组ID 查找分组
            $group = Sentry::findGroupById($input['id']);
            $newArr=array();
            foreach ($group->permissions as $key => $value) {
                $newArr[$key]=0;
            }
            $group->permissions=$newArr;
            $group->save();
            // 更新分组详情
            $group->name = $input['name'];
            $group->permissions =$roles;
            // 更新分组
            if ($group->save())
            {
                $ret = [
                    'status' => 200,
                    'msg' => '角色配置/修改成功',
                	'tabid'=>'group'
                ];
            }else{
                $ret = [
                    'status' => 300,
                    'msg' => '角色配置/修改失败,请重试!',
                ];
            }
        }
        catch (\Cartalyst\Sentry\Groups\NameRequiredException $e) {
            $ret = [
                'status' => 300,
                'msg' => '角色名称必须存在,请重试!',
            ];
        }
        catch (\Cartalyst\Sentry\Groups\GroupExistsException $e) {
            $ret = [
                'status' => 300,
                'msg' => '角色已经存在,请重试!',
            ];
        }
        catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
            $ret = [
                'status' => 300,
                'msg' => '角色不存在,请重试!',
            ];
        }
        return $ret;
    }

    //删除用户组
    public function delGroup(){
        $input=Input::all();
        $id = explode(",", $input['id']);

		try {
            foreach($id as $v){
                if($v){
                    Sentry::findGroupById($v)->delete();
                }
            }
		} catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
            $ret = [
                'status' => 300,
                'msg' => '用户组不存在，请稍后重试！',
            ];
			
    		return $ret;
        }
        $ret = [
            'status' => 200,
            'msg' => '用户组删除成功！',
        ];
        return $ret;
    }



    //权限路径列表
    public function role(Request $request){
    	if($request->isMethod('post')){
	        $auth=Auth::get();
	        //$data=catlist($auth,'a_id','_cate_name');
			return $auth->toJson();
		}else{
			$auth=Auth::get();
			$auths=catlist($auth,'a_id','_cate_name');

			return view('admin.user.role',['auths'=>$auths]);
		}
    }
	
	public function roleEdit(Request $request){
		$input=Input::all();
		$obj=json_decode($input['json']);
		if($request->isMethod('post') && count($obj)>0){
			if(!isset($obj[0]->id)){//单个数据添加处理，禁止了多个数据
				$auth=Auth::where('name',$obj[0]->name)->first();
				$data['name']=$obj[0]->name;
				$data['role']=$obj[0]->role;
				$data['a_id']=$obj[0]->a_id?$obj[0]->a_id:0;
				//$data['activated']=$obj[0]->activated?1:0;
				$data['showed']=$obj[0]->showed?1:0;
	            if(!$auth){
	                if(!$data['name'] || !$data['role']){
	                	$ret = [
			                'status' => 300,
			                'msg' => '权限名称和详细不能为空！',
			            ];
	                }
	                if(Auth::insertGetId($data)){
	                	$ret = [
			                'status' => 200,
			                'msg' => '权限添加成功！',
			            ];
	                }else{
	                	$ret = [
			                'status' => 300,
			                'msg' => '权限添加失败！',
			            ];
	                }
            	}else{
                	$ret = [
		                'status' => 300,
		                'msg' => '权限名称已经存在！',
		            ];
	            }
			}else{
				
				$ret = [
	                'status' => 200,
	                'msg' => '权限修改成功！',
					'tabid'=>'role'
	            ];
				
				foreach($obj as $k=>$v){
					$data[$k]['id']=$v->id;
					$data[$k]['name']=$v->name;
					$data[$k]['role']=$v->role;
					$data[$k]['orders']=$v->orders;
					$data[$k]['a_id']=$v->a_id?$v->a_id:0;
					//$data[$k]['activated']=$v->activated?1:0;
					$data[$k]['showed']=$v->showed?1:0;
					
					$auth = Auth::where('id',$data[$k]['id'])->first();
		            if(!$data[$k]['name'] || !$data[$k]['role']){
		            	$ret = [
			                'status' => 300,
			                'msg' => '权限名称和详细不能为空！',
			            ];
						return $ret;
		            }
					if(!$auth){
						$ret = [
			                'status' => 300,
			                'msg' => '权限不存在,请重试!',
			            ];
						return $ret;
					}
					$auths=Auth::get();
					$aid=getChildsId($auths,$data[$k]['id'],$aidname='a_id');
					$aid[]=$data[$k]['id'];
					if(in_array($data[$k]['a_id'],$aid)){
						$ret = [
			                'status' => 300,
			                'msg' => '权限上级出错,禁止修改！',
			            ];
					}else{
						if(!Auth::where('id',$data[$k]['id'])->update($data[$k])){
							$ret = [
				                'status' => 300,
				                'msg' => '权限修改失败！',
				            ];
						}
					}
				}
			}
			return $ret;
		}else{
			$ret = [
                'status' => 300,
                'msg' => '没有修改的项！',
            ];
			return $ret;
		}
	}

    //删除权限
    public function delRole(){
        $input=Input::all();
		$auth=Auth::get();
		foreach(json_decode($input['json']) as $v){
			$ids[]=$v->id;
		}
		foreach($ids as $r){
			$id[]=$r;
			foreach(getChildsId($auth,$pid=$r,$aidname='a_id') as $s){
				$id[]=$s;
			}
		}
		$id=(array_unique($id));
		$ids=implode(',',$id);
		if(Auth::destroy($ids)){
			$ret = [
                'status' => 200,
                'msg' => '权限删除成功！',
            ];
		}else{
			$ret = [
                'status' => 300,
                'msg' => '权限删除失败，请稍后重试！',
            ];
		}
        return $ret;
    }
}
